<template lang="html">
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="search"
        placeholder="输入分类关键字搜索"
        class="filter-item"
        style="width: 400px;"
      >
        <i slot="prefix" class="el-input__icon el-icon-search" />
      </el-input>
      <el-button class="filter-item" type="success" icon="el-icon-edit" @click="handleAdd">
        新增分类
      </el-button>
    </div>
    <el-table
      ref="tree"
      v-loading="listLoading"
      :data="filterCategories"
      style="width: 100%;margin-bottom: 20px;"
      row-key="gid"
      border
      :default-expand-all="expandAll"
      :tree-props="{children: 'children', hasChildren: true}"
    >
      <el-table-column
        prop="name"
        label="名称"
        sortable
      />
      <el-table-column align="center" label="logo">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.logo&&scope.row.logo!==''"
            style="width: 60px;"
            :src="scope.row.logo"
            :preview-src-list="[scope.row.logo]"
          >
            <div slot="placeholder" class="image-slot" style="width:60px;height:30px;text-align:center;line-height:30px;">
              <i class="dot el-icon-loading" style="font-size:20px;" />
            </div>
          </el-image>
          <span v-else>暂无图片</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="链接">
        <template slot-scope="scope">
          <el-button v-clipboard:copy="`/pages/product/list?cateId=${scope.row.gid}&title=${scope.row.name}`" v-clipboard:success="clipboardSuccess" size="mini">拷贝地址</el-button>
        </template>
      </el-table-column>
      <el-table-column
        prop="isShow"
        label="是否显示"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isShow"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="saveCategory(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleAdd(scope.row)"
          >
            添加子分类
          </el-button>
          <el-button
            size="mini"
            type="primary"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="delCategory(scope.row)"
          >
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="temp" label-position="right" label-width="80px" style="width: 80%; margin-left:50px;">
        <el-form-item label="父级分类" prop="toCategoryId">
          <el-cascader
            v-model="temp.toCategoryId"
            placeholder="输入分类关键字搜索"
            :options="categories"
            :show-all-levels="true"
            :clearable="true"
            :props="{value:'gid',label:'name',expandTrigger: 'hover', checkStrictly: true, emitPath: false}"
            filterable
          />
        </el-form-item>
        <el-form-item label="分类名" :rules="{required: true, message: '请输入分类名', trigger: 'change'}" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="分类图片">
          <Single-image v-model="temp.logo" :single-image="true" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="saveCategory()">
          确认
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { deepClone } from '@/utils'
import clipboard from '@/directive/clipboard/index.js'
import { getCategory, saveCategory, delCategory } from '@/api/catetory'
import SingleImage from '@/components/Upload/SingleImage'
export default {
  components: {
    SingleImage
  },
  directives: {
    clipboard
  },
  data() {
    return {
      search: '',
      categories: [],
      expandAll: false,
      listLoading: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      temp: {
        gid: '',
        name: '',
        toCategoryId: '',
        logo: '',
        isShow: true
      }
    }
  },
  computed: {
    filterCategories() {
      var search = this.search
      function check(children) {
        children.forEach(function(item, index) {
          if (item.children && item.children.length > 0 && !item.name.toLowerCase().includes(search.toLowerCase())) {
            item.children = check(item.children)
          }
        })
        return children.filter(data => data.name.toLowerCase().includes(search.toLowerCase()) || (data.children && data.children.length > 0))
      }
      const categories = check(deepClone(this.categories))
      return categories
    }
  },
  created() {
    this.getcategories()
  },
  methods: {
    clipboardSuccess() {
      this.$message({
        message: '复制成功',
        type: 'success',
        duration: 1500
      })
    },
    handleEdit(row) {
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.temp = {
        gid: row.gid,
        name: row.name,
        toCategoryId: row.toCategoryId,
        logo: row.logo || '',
        isShow: row.isShow
      }
    },
    handleAdd(row) {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.temp = {
        gid: '',
        name: '',
        toCategoryId: row ? row.gid : ''
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    getcategories() {
      this.listLoading = true
      getCategory().then(res => {
        this.categories = res.result
        this.listLoading = false
      })
    },
    saveCategory(data) {
      if (data && typeof (data) === 'object') { // 有参数的时候
        saveCategory(data).then(() => {
          this.$message.success('保存成功')
          this.getcategories()
        })
      } else if (!data) { // 没有参数的时候
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            saveCategory(this.temp).then(() => {
              this.$message.success('保存成功')
              this.getcategories()
            })
            this.dialogFormVisible = false
          }
        })
      } else {
        this.$message({
          type: 'error',
          message: '程序错误'
        })
      }
    },
    delCategory(row) {
      this.$confirm(`是否确认要删除${row.name}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delCategory({ gid: row.gid }).then(() => {
          this.$message.success('删除成功！')
          this.getcategories()
        })
      }).catch(() => {})
    }
  }
}
</script>
